package server.bootstrap;

import server.process.RequestProcessor;

import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Hugh
 * @Date: 2020/6/1
 */
public class Minicat30ThreadPoolBootStrap extends BaseBootStrap{

    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 多线程改造（使用线程池）
     * @param socket socket
     * @throws Exception
     */
    @Override
    protected void doHandle(Socket socket) throws Exception {

        RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
        //requestProcessor.start();
        threadPoolExecutor.execute(requestProcessor);
    }

    @Override
    protected void init() throws Exception {
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    @Override
    protected void loadServlet() throws Exception {
        commonloadServlet();
    }
}
